package com.gljr.exam.web;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;

import com.gljr.exam.dao.ExamPaperQuestionRepository;
import com.gljr.exam.dao.InviteCodeRepository;
import com.gljr.exam.dao.TotalPointsRepository;
import com.gljr.exam.dao.UserRepository;
import com.gljr.exam.domain.ExamPaperQuestion;
import com.gljr.exam.domain.InviteCode;
import com.gljr.exam.domain.User;
import com.gljr.exam.tools.CipherUtil;
import com.gljr.exam.tools.ExamUniTools;
import com.gljr.exam.web.form.ExamPaperForm;
import com.gljr.exam.web.form.InviteCodeForm;
import com.gljr.exam.web.form.LoginForm;
import com.gljr.exam.web.form.ModifyForm;
import com.gljr.exam.web.form.RegisterForm;
import com.gljr.exam.web.form.UploadExamForm;

@Controller
@SessionAttributes("user")
public class IndexController {

	@Autowired
	private UserRepository userRepository;

	@ModelAttribute("loginForm")

	public LoginForm initForm() {
		System.out.println("initForm...");
		return new LoginForm();
	}

	@Autowired
	private ExamPaperQuestionRepository examPaperQuestionRepository;

	@Autowired
	private InviteCodeRepository inviteCodeRepository;

	@Autowired
	private TotalPointsRepository totalPointsRepository;

	@RequestMapping(path = "/", method = RequestMethod.GET)
	public String index(@ModelAttribute LoginForm form, Model model) {
		model.addAttribute("webroot", "/templates/");

		return "index";
	}

	@RequestMapping(path = "/login", method = RequestMethod.GET)
	public String login() {
		return "login";
	}

	@RequestMapping(path = "/login", method = RequestMethod.POST)
	public String doLogin(@ModelAttribute LoginForm form, Model model) {

		User user = userRepository.findByUsernameIgnoreCase(form.getUsername());
		String psw = form.getPassword();// 明文
		String pswMD5 = user.getPassword();
		System.out.println("用户输入---->" + psw + "数据库MD5---->" + pswMD5);
		if (user == null || !CipherUtil.validatePassword(pswMD5, psw) || form.getPassword() == "") {
			model.addAttribute("err", "用户名或密码错误!");
			return "login";
		}

		model.addAttribute("user", user);
		return "redirect:/";
	}

	@RequestMapping(path = "/invitecode", method = RequestMethod.GET)
	public String invitecode(InviteCodeForm form, Model model) {
		if (model.asMap().get("user") == null) {
			return "redirect:/errpage";
		}

		return "invitecode";
	}

	@RequestMapping(path = "/invitecode", method = RequestMethod.POST)
	public String doInvitecode(@ModelAttribute InviteCodeForm form, Model model) {
		InviteCode inviteCode = inviteCodeRepository.findByInviteCode(form.getInvitecode());
		System.out.println("打印出用户输入的邀请码---->" + form.getInvitecode());
		Boolean bl = inviteCodeRepository.getIfInviteCodeisBoolean(form.getInvitecode());
		if (inviteCode == null || !inviteCode.getInviteCode().equals(form.getInvitecode()) || bl == false) {
			model.addAttribute("err", "您输入的邀请码不存在或者已失效,请联系考试主办方!");
			return "invitecode";
		} else if (inviteCode.getInviteCode().equals(form.getInvitecode())) {
			System.out.println("打印出数据库查询出的邀请码---->" + inviteCode.getInviteCode());
			String currentUsername = ExamUniTools.getSessionUsername(model);
			userRepository.setUserExamStatus(ExamUniTools.getSessionUsername(model), true);// 使用完邀请码
																							// 设置用户考试状态
			inviteCodeRepository.setInviteCodeStatus(form.getInvitecode(), currentUsername, false);
			// 设置邀请码使用状态, 使用完邀请码,ture代表不作废,false代表作废
			return "redirect:/startexam";
		}
		return "invitecode";
	}

	@RequestMapping(path = "/startexam", method = RequestMethod.GET) // 开始考试
	public String startexam(@ModelAttribute ExamPaperForm form, Model model) {
		// String currentUsername = ExamUniTools.getSessionUsername(model);
		if (model.asMap().get("user") == null) {
			return "redirect:/errpage";
		} else if (userRepository.getIfUserExamStatus(ExamUniTools.getSessionUsername(model)) == false) {
			model.addAttribute("err", "您无权答题");
			return "redirect:/errpagetips";
		}
		Long maxidlong = examPaperQuestionRepository.findMaxID();
		int maxnum = new Long(maxidlong).intValue();// 查找出最大的ID值作为随机数最大范围
		long[] arr = ExamUniTools.genArr(maxnum);// 生成随机试卷所需随机数组,maxnum代表有这么多个数值,返回maxnum长度数组

		List<Long> listLong = new ArrayList<Long>();// 此集合保存产生随机提序号的数组
		for (int i = 0; i <= 50; i++) { // 试卷题目数量
			System.out.println("long数组遍历---->" + arr);
			ExamPaperQuestion examPaperQuestion = examPaperQuestionRepository.findExquestionByExnum(arr[i]);
			System.out.println("long数组遍历对象---->" + examPaperQuestion.getExquestion());
			model.addAttribute("exampaperquestion" + i, examPaperQuestion);
			System.out.println("试卷exnum---->" + examPaperQuestion.getExnum());
			listLong.add(examPaperQuestion.getExnum());// 添加随机题号到数组listlong去

		}
		model.addAttribute("arrlong", listLong);// 往freemarker传出随机题号数组在前端显示
		for (long l : listLong) {
			System.out.println("打印出l---->" + l);
		}

		userRepository.setUserExamStatus(ExamUniTools.getSessionUsername(model), false);// 设置考试状态,false表示考完不能再考,防止在考试中刷新

		return "startexam";
	}

	@RequestMapping(path = "/register", method = RequestMethod.GET)
	public String register() {
		return "register";
	}

	@RequestMapping(path = "/register", method = RequestMethod.POST)
	public String doRegister(@ModelAttribute RegisterForm form, Model model) {
		User user = userRepository.findByUsernameIgnoreCase(form.getUsername());
		// String psw = user.getPassword();
		if (user != null) {
			model.addAttribute("err", "用户名已存在!");
			return "register";
		}
		if (form.getUsername().length() < 4) {
			model.addAttribute("err", "字符长度非法,至少4字以上字符!");
			return "register";
		}
		if (form.getUsername() == null || form.getUsername() == "") {
			model.addAttribute("err", "用户名为空!");
			return "register";
		}
		if (form.getPassword() == "" || form.getPassword2() == "") {
			model.addAttribute("err", "密码不能为空!");
			return "register";
		}
		if (!form.getPassword().equals(form.getPassword2())) {
			model.addAttribute("err", "两次输入的密码不一致");
			return "register";
		}

		String psw = form.getPassword();// 明文psw
		String pswMD5 = CipherUtil.generatePassword(psw);

		userRepository.save(new User(form.getUsername(), pswMD5, form.getRealname(), false, false));
		model.addAttribute("success", "注册成功!");
		return "redirect:/success";
	}

	@RequestMapping(path = "/success", method = RequestMethod.POST)
	public String doSuccess(@ModelAttribute RegisterForm form, Model model) {
		return "success";
	}

	@RequestMapping(path = "/success", method = RequestMethod.GET)
	public String Success(@ModelAttribute RegisterForm form, Model model) {
		return "success";
	}

	@RequestMapping(path = "/uploadexam", method = RequestMethod.POST)
	public String doUploadExam(@ModelAttribute UploadExamForm form, Model model) {
		Long maxexampaperID = examPaperQuestionRepository.findMaxID();
		Long maxexampaperIDAdd1 = null;
		try {
			maxexampaperIDAdd1 = maxexampaperID + 1L;
		} catch (Exception e) {

			e.printStackTrace();
		}
		System.out.println("最大的题库编号为POST---->" + maxexampaperID);
		ExamPaperQuestion examPaperQuestion = examPaperQuestionRepository.findByExquestion(form.getExquestion());
		if (form.getExquestion() == "" || form.getExopta() == "" || form.getExoptb() == "" || form.getExkey() == "") {
			model.addAttribute("err", "全部不能为空!");
			model.addAttribute("maxexampaperIDAdd1", maxexampaperIDAdd1);
			return "uploadexam";
		} else if (examPaperQuestion != null) {
			model.addAttribute("err", "题目已经存在!");
			model.addAttribute("maxexampaperIDAdd1", maxexampaperIDAdd1);
			return "uploadexam";
		}

		examPaperQuestionRepository.save(new ExamPaperQuestion(form.getExquestion(), form.getExopta(), form.getExoptb(),
				form.getExoptc(), form.getExoptd(), form.getExkey(), form.getExnum()));

		// examPaperQuestionRepository.save(new
		// ExamPaperQuestion(form.getExnum(), form.getExquestion(),
		// form.getExopta(),
		// form.getExoptb(), form.getExkey()));四个选项的
		return "redirect:/uploadsuccess";
	}

	@RequestMapping(path = "/uploadexam", method = RequestMethod.GET)
	public String uploadExam(@ModelAttribute UploadExamForm form, Model model) {
		if (model.asMap().get("user") == null) {
			// model.addAttribute("erruploadexam", "管理员请先登录!");
			return "redirect:/errpagetips";
		}
		String currentUsername = ExamUniTools.getSessionUsername(model);
		boolean adminflag = userRepository.getIfAdmin(currentUsername);
		if (adminflag) {
			System.out.println("打印出是否为admin---->" + adminflag);
		} else {
			return "redirect:/errpage";
		}

		Long maxexampaperID = examPaperQuestionRepository.findMaxID();
		Long maxexampaperIDAdd1;
		try {
			maxexampaperIDAdd1 = maxexampaperID + 1L;
			model.addAttribute("maxexampaperIDAdd1", maxexampaperIDAdd1);
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("查询出整个列表---->" + totalPointsRepository.findAll().toString());
		return "uploadexam";
	}

	@RequestMapping(path = "/uploadsuccess", method = RequestMethod.GET)
	public String uploadExamSuccess() {
		return "uploadsuccess";
	}

	@RequestMapping(path = "/modify", method = RequestMethod.POST)
	public String doModify(@ModelAttribute ModifyForm form, Model model) {
		User user = userRepository.findByUsernameIgnoreCase(form.getUsername());
		String psw = form.getPassword();// 明文
		String pswMD5 = user.getPassword();
		System.out.println("用户输入---->" + psw + "数据库MD5---->" + pswMD5);
		if (user == null || !CipherUtil.validatePassword(pswMD5, psw) || form.getPassword() == "") {
			model.addAttribute("err", "用户名或密码错误!");
			return "modify";
		}

		if (form.getPassword2() == "" || form.getPassword3() == "") {
			model.addAttribute("err", "密码不能为空!");
			return "modify";
		}

		if (!form.getPassword2().equals(form.getPassword3())) {
			model.addAttribute("err", "两次输入的密码不一致");
			return "modify";
		}

		String pswMD5New = CipherUtil.generatePassword(form.getPassword2());
		String username = user.getUsername();
		userRepository.updatePSW(username, pswMD5New);
		model.addAttribute("err", "密码修改成功!");

		return "modify";
	}

	@RequestMapping(path = "/modify", method = RequestMethod.GET)
	public String Modify() {
		return "modify";

	}

	@RequestMapping(path = "/errpage", method = RequestMethod.GET)
	public String errPage(@ModelAttribute UploadExamForm form, Model model) {
		model.addAttribute("err", "请先登录!");
		return "errpage";
	}

	@RequestMapping(path = "/errpagetips", method = RequestMethod.GET)
	public String errPageTips(@ModelAttribute ExamPaperForm form, Model model) {
		model.addAttribute("err", "您没有权限!");
		return "errpagetips";
	}

	@RequestMapping(path = "/totalpoints", method = RequestMethod.GET)
	public String totalPoints(@ModelAttribute UploadExamForm form, Model model) {

		model.addAttribute("totalPoints", totalPointsRepository.findAll().toString());
		return "totalpoints";
	}

	@RequestMapping(path = "/logout")
	public String logout(SessionStatus status) {
		status.setComplete();
		return "redirect:/";
	}
}
